<template>
  <div class="layout">
  <div class="main-box">
    <div class="upper-box">
      <div class="left-middle-box">
        <div class="small-box total-purchase">{{ totalPurchase }}: {{ purchaseValue }}</div>
        <div class="small-box total-purchase">{{ totalPrice }}月采购总金额: {{ recentMonthPurchaseAmount }}</div>
        <div class="small-box total-suppliers">{{ totalSuppliers }}: {{ supplierValue }}</div>
        <div class="small-box total-business">{{ totalBusiness }}: {{ businessValue }}</div>
      </div>
      <div class="right-middle-box">
        <div class="small-box board">{{ board }}: {{ boardValue }}</div>
        <div class="small-box tube">{{ tube }}: {{ tubeValue }}</div>
        <div class="small-box rod">{{ rod }}: {{ rodValue }}</div>
        <div class="small-box mirror">{{ mirror }}: {{ mirrorValue }}</div>
        <div class="small-box ring">{{ ring }}: {{ ringValue }}</div>
        <div class="small-box welding-needle">{{ weldingNeedle }}: {{ weldingNeedleValue }}</div>
      </div>
    </div>
    <div class="lower-box">
      <div class="left-middle-box">
        <div id="line-chart" style="width: 100%; height: 400px;"></div>
      </div>
      <div class="right-middle-box">
        <div id="pie-chart" style="width: 100%; height: 400px;"></div>
      </div>
    </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, computed, onBeforeMount } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import { statistics } from "./service/api"

export default defineComponent({
  components: {},
  setup() {
    const state = reactive({
      totalPurchase: '采购总数量',
      totalSuppliers: '合作供应商总数',
      totalBusiness: '合作业务总数',
      totalPrice: null,
      board: '板类',
      tube: '管类',
      rod: '棒类',
      mirror: '镜类',
      ring: '环类',
      weldingNeedle: '其他类',
      // 具体数字
      purchaseValue: null, //采购总数量（用productQuantity相加）
      supplierValue: null,//供应商总数量
      businessValue: null,//业务总数
      recentMonthPurchaseAmount: null,//一个月总价
      boardValue: null,//板类数量（当isSpecificationType = 1时，productQuantity相加）
      tubeValue: null,//管类数量（当isSpecificationType = 2时，productQuantity相加）
      rodValue: null,//棒类数量(当isSpecificationType = 3时，productQuantity相加)
      mirrorValue: null,//镜类数量(当isSpecificationType = 4时，productQuantity相加)
      ringValue: null,//环类数量(当isSpecificationType = 5时，productQuantity相加)
      weldingNeedleValue: null,//点焊针类数量(当isSpecificationType = 6时，productQuantity相加)
      // 图表数据
      chartData: [
        { value: null, name: '板类' },
        { value: null, name: '管类' },
        { value: null, name: '棒类' },
        { value: null, name: '镜类' },
        { value: null, name: '环类' },
        { value: null, name: '其他类' },
      ],
      lineData: [] // 最近两周采购数量（比如今天是5月13号，那么就以purchaseTime = 2015.5.13为第14个数据，时间是Date类型）
                                                    //然后依次减一天，返回第13个数据为5月12号的productQuantity总和；再减一天，返回第12个数据为5月11号的
                                                    //的productQuantity总和，以此类图。这个数据是个数组，参考我左边的lineData数组，返回这样的数组给我
    });
    // 计算最近14天的日期标签
    const dateLabels = computed(() => {
      const labels = [];
      const now = new Date();
      
      for (let i = 14; i >= 1; i--) {
        const date = new Date();
        date.setDate(now.getDate() - i + 1); // 计算前i天的日期
        const month = date.getMonth() + 1;
        const day = date.getDate();
        labels.push(`${month}月${day}日`);
      }
      
      return labels;
    });
    const initData =() =>{
      statistics().then((res)=>{
        console.log("statistics",res.data)
        state.purchaseValue = res.data.purchaseValue
        state.supplierValue = res.data.supplierValue
        state.businessValue = res.data.businessValue
        state.boardValue = res.data.boardValue
        state.tubeValue = res.data.tubeValue
        state.rodValue = res.data.rodValue
        state.mirrorValue = res.data.mirrorValue
        state.ringValue = res.data.ringValue
        state.recentMonthPurchaseAmount = res.data.recentMonthPurchaseAmount
        state.weldingNeedleValue = res.data.weldingNeedleValue
        state.chartData[0].value = res.data.boardValue
        state.chartData[1].value = res.data.tubeValue
        state.chartData[2].value = res.data.rodValue
        state.chartData[3].value = res.data.mirrorValue
        state.chartData[4].value = res.data.ringValue
        state.chartData[5].value = res.data.weldingNeedleValue
        state.lineData = res.data.lineData
        console.log("state.chartData",state.chartData)
        console.log("state.lineData",state.lineData)
        initChat()
      })
    }
    const initChat = () =>{
      // 初始化折线图（原饼图位置）
      const lineChart = echarts.init(document.getElementById('line-chart'));
      const lineOption = {
        title: {
          text: '最近两周采购数量',
          subtext: '单位: 件',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dateLabels.value // 使用动态生成的日期标签
        },
        yAxis: {
          type: 'value',
          min: 100
        },
        series: [
          {
            data: state.lineData,
            type: 'line',
            smooth: true,
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      };
      lineChart.setOption(lineOption);

      // 初始化饼状图（原折线图位置）
      const pieChart = echarts.init(document.getElementById('pie-chart'));
      const pieOption = {
        title: {
          text: '产品类别分布',
          subtext: '单位: 件',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} 件 ({d}%)'
        },
        series: [
          {
            name: '类别数量',
            type: 'pie',
            radius: '60%',
            data: state.chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      pieChart.setOption(pieOption);
    }
    onBeforeMount((row) => {
      state.totalPrice = new Date().getMonth() + 1
      initData()
    })
    onMounted(() => {
    })
    return {
      ...toRefs(state)
    };
  }
});
</script>

<style scoped>
.layout {
  width: 100%;
  height: 100%;
  background-color: #F5F6F9;
  padding: 20px;
  box-sizing: border-box;
}
.main-box{
    width: 98%;
    height: 100%;
    background-color: #FFFFFF;
    margin: auto;
}
.upper-box, .lower-box {
  display: flex;
  max-height: 532px;
  justify-content: space-between;
  margin-bottom: 20px;
  gap: 20px;
}

.left-middle-box, .right-middle-box {
  flex: 1;
  background-color: #FFFFFF;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.left-middle-box {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.right-middle-box {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 15px;
}

.small-box {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  padding: 15px;
  border-radius: 6px;
  background-color: #f8f9fa;
  transition: all 0.3s;
}

.small-box:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.total-purchase { background-color: rgba(224, 230, 237, 0.5); }
.total-suppliers { background-color: rgba(210, 222, 236, 0.5); }
.total-business { background-color: rgba(195, 214, 235, 0.5); }

.board { background-color: rgba(224, 230, 237, 0.3); }
.tube { background-color: rgba(210, 222, 236, 0.3); }
.rod { background-color: rgba(195, 214, 235, 0.3); }
.mirror { background-color: rgba(180, 206, 234, 0.3); }
.ring { background-color: rgba(165, 198, 233, 0.3); }
.welding-needle { background-color: rgba(150, 190, 232, 0.3); }
</style>